<?php
/**
 * Created by PhpStorm.
 * User: wuanjie
 * Date: 16-5-25
 * Time: 上午11:32
 */
class wechatCard {

    const API_GETUSERCARD = 'https://api.weixin.qq.com/card/user/getcardlist?access_token=%s';
    const API_GETCARDSTATUS = 'https://api.weixin.qq.com/card/code/get?access_token=%s';
    const API_GETCARDDETAIL = 'https://api.weixin.qq.com/card/get?access_token=%s';
    const API_CONSUMECARD = 'https://api.weixin.qq.com/card/code/consume?access_token=%s';

    /**
     * @param $openid
     * @return mixed
     */
    public function getUserCard($openid) {
        $requestData = array(
            'openid' => $openid,
            'card_id' => ''
        );

        return $this->access(self::API_GETUSERCARD, json_encode($requestData));
    }

    /**
     * @param $cardid
     * @param $code
     * @return mixed
     */
    public function getCardStatus($cardid, $code) {
        $requestData = array(
            'card_id' => $cardid,
            'code' => $code,
            'check_consume' =>true
        );
        return $this->access(self::API_GETCARDSTATUS, json_encode($requestData));
    }

    /**
     * @param $cardid
     * @return mixed
     */
    public function getCardDetail($cardid) {
        $requestData = array(
            'card_id' => $cardid
        );
        return $this->access(self::API_GETCARDDETAIL, json_encode($requestData));
    }

    /**
     * @param $openid
     * @return array
     */
    public function getUseableCard($openid) {

        $usercardsObj = self::getUserCard($openid);
        $result = array();
        if ( $usercardsObj->errcode == 0 && $usercardsObj->errmsg == 'ok' ) {
            foreach ( $usercardsObj->card_list as $value ) {
                $card = self::getCardStatus($value->card_id, $value->code);
                if ($card->can_consume == true && $card->user_card_status == 'NORMAL') {
                    $cardinfo =  $this->getCardDetail($card->card->card_id);
                    $base_info= $cardinfo->card->cash->base_info;
                    $result[] = array('cardID'=>$base_info->id, 'card_title'=>$base_info->title,'card_code'=>$value->code,'card_fee'=>$cardinfo->card->cash->reduce_cost);
                }
            }
        }
        //print_R($cardinfo);exit;
        return $result;
    }
    
    public function consumeCard($code) {
        $requestData = array(
            'code' => $code
        );
        return $this->access(self::API_CONSUMECARD, json_encode($requestData));
    }

    /**
     * @param $api
     * @param string $requestData
     * @return mixed
     */
    function access($api, $requestData = '') {
        $token = Tools_help::getToken();
        //$token = 'wP1zOFju5jfnqEJyQoeiDUD0UAawL6a1Tbr00DJkXWOv0ZUzJi3nsLqbvItmTDGgDB2gnPYS-erSsn6RU3MDMMVVtTZENwhlZLOLlUiV_HIJLZdAHAACQ';
        $url = sprintf($api, $token);
        $result = Tools_help::weixinCurlPost($url, $requestData);
        $object = json_decode($result);
        return $object;
    }
}